package com.action;

import com.bean.ResponseBean;
import com.pojo.Admin;
import com.service.AdminService;
import com.service.AdminServiceImp;
import com.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@RequestMapping("/admin")
@RestController
@CrossOrigin("*")
public class AdminAction {

    @Autowired
    private AdminServiceImp adminService;

    /**
     * 登录：判断账号密码是否正确
     * @param username  用户名
     * @param password  密码
     * @return  用户对象
     */
    @RequestMapping("/login")
    public ResponseBean login(HttpServletRequest request, String username, String password) {
        Admin admin = adminService.login(username,password);
        request.getSession().setAttribute("admin",admin);
        return new ResponseBean(admin!=null ? 200:500,"用户名或密码错误",admin);
    }

    @RequestMapping("/updateAdmin")
    public ResponseBean updateAdmin(HttpServletRequest request, String oldpassword, String password) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null){
            return new ResponseBean(403,"没有权限",null);
        }
        String oldPwd = admin.getPassword();
        String oldPwdDB = PasswordUtil.jiami(oldpassword);
        if (oldPwd.equals(oldPwdDB)==false){
            return new ResponseBean(500,"旧密码不正确",null);
        }
        String newPwd = PasswordUtil.jiami(password);
        admin.setPassword(newPwd);
        adminService.updateById(admin);
        return new ResponseBean(200,"修改密码",null);
    }

}
